/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sqlserver;

import java.io.File;
import java.io.RandomAccessFile;


/**
 *
 * @author ROMANCE
 */
public class Utils {
    
  public static String replaceAll(String input, String forReplace,
                                  String replaceWith) {
    if( input == null )
      return "null";
      //return null;
    StringBuilder result = new StringBuilder();
    boolean hasMore = true;
    while (hasMore) {
      int start = input.indexOf(forReplace);
      int end = start + forReplace.length();
      if (start != -1) {
                result.append(input.substring(0, start)).append(replaceWith);
        input = input.substring(end);
      }
      else {
        hasMore = false;
        result.append(input);
      }
    }
    if (result.toString().equals(""))
      return input; //nothing is changed
    else
      return result.toString();
  }


  public static String handleQuotedString(String quotedString) {
    if( quotedString == null )
      return "null";
      //return null;
    String retVal = quotedString;
    if ( (retVal.startsWith("'") && retVal.endsWith("'"))) {
      if (!retVal.equals("''")) {
        retVal = retVal.substring(retVal.indexOf("'") + 1,
                                  retVal.lastIndexOf("'"));
      }
      else {
        retVal = "";
      }
    }
    //else {
    //  if( retVal.equals("null") )
    //    retVal = null;
    //}
    return retVal;
  }


    public static String getAbsolutePathFromDatabaseURL(String urlPrefix,
        String loaderJobFile, String urlToDatabase, boolean fileSystemDatabase) {

    if(fileSystemDatabase==true){
        String pathToDatabase=urlToDatabase.substring(urlPrefix.length());
        File file=new File(pathToDatabase);
        if (!file.isAbsolute()){
        pathToDatabase=loaderJobFile + pathToDatabase;
        File absolutePath=new File(pathToDatabase);
        try {
            pathToDatabase=absolutePath.getCanonicalPath();
        }
        catch (Exception ex) {
        }
        urlToDatabase = urlToDatabase.substring(0, (urlPrefix.length())) +
                        pathToDatabase;
        }
    }
    return urlToDatabase;
    }

    public static void log(String msg) {
        try {
                File file = new File("c:/log.txt");
                if (!file.exists()) {
                file.createNewFile();
                }
                try (RandomAccessFile fileLogr = new RandomAccessFile("c:/log.txt", "rw")) {
                    fileLogr.seek(fileLogr.length());
                    fileLogr.writeBytes( msg + "\r\n");
                }
            }
        catch (Exception ex) {
        }
    }
}

